﻿using System.IO;
using JustTest.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;

namespace JustTest.Account
{
    public partial class Manage : System.Web.UI.Page
    {
        protected string SuccessMessage
        {
            get;
            private set;
        }

        protected bool CanRemoveExternalLogins
        {
            get;
            private set;
        }

        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                //fill the change names textboxes with current names
                //!!! must refactore this 
                var currentUser = new JustTestDb().Users.Find(User.Identity.GetUserId());

                this.newFirstName.Text = currentUser.FirstName;
                this.newLastName.Text = currentUser.LastName;

                // Determine the sections to render
                ILoginManager manager = new IdentityManager(new IdentityStore(new JustTestDb())).Logins;
                if (manager.HasLocalLogin(User.Identity.GetUserId()))
                {
                    changeProfilePicture.Visible = true;
                    changePasswordHolder.Visible = true;
                    changeUsernamePlaceholder.Visible = true;
                }
                else
                {
                    setPassword.Visible = true;
                    changePasswordHolder.Visible = false;
                }
                CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1;

                // Render success message
                var message = Request.QueryString["m"];
                if (message != null)
                {
                    // Strip the query string from action
                    Form.Action = ResolveUrl("~/Account/Manage.aspx");

                    SuccessMessage =
                        message == "ChangePwdSuccess"
                            ? "Your password has been changed."
                            : message == "SetPwdSuccess"
                                ? "Your password has been set."
                                : message == "RemoveLoginSuccess"
                                    ? "The account was removed."
                                    : message == "SetNamesSuccess"
                                        ? "Your names have been updated"
                                        :message == "SetPicSuccess"
                                        ? "File uploaded succsefully"
                                        : String.Empty;
                    
                    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                }
            }
        }

        protected void ChangePassword_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                IPasswordManager manager = new IdentityManager(new IdentityStore(new JustTestDb())).Passwords;
                IdentityResult result = manager.ChangePassword(User.Identity.GetUserName(), CurrentPassword.Text,
                    NewPassword.Text);
                if (result.Success)
                {
                    Response.Redirect("~/Account/Manage.aspx?m=ChangePwdSuccess");
                }
                else
                {
                    AddErrors(result);
                }
            }
        }

        protected void SetPassword_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Create the local login info and link the local account to the user
                ILoginManager manager = new IdentityManager(new IdentityStore(new JustTestDb())).Logins;
                IdentityResult result = manager.AddLocalLogin(User.Identity.GetUserId(), User.Identity.GetUserName(),
                    password.Text);
                if (result.Success)
                {
                    Response.Redirect("~/Account/Manage.aspx?m=SetPwdSuccess");
                }
                else
                {
                    AddErrors(result);
                }
            }
        }

        public IEnumerable<IUserLogin> GetLogins()
        {
            ILoginManager manager = new IdentityManager(new IdentityStore(new JustTestDb())).Logins;
            var accounts = manager.GetLogins(User.Identity.GetUserId());
            CanRemoveExternalLogins = accounts.Count() > 1;
            return accounts;
        }

        public void RemoveLogin(string loginProvider, string providerKey)
        {
            ILoginManager manager = new IdentityManager(new IdentityStore(new JustTestDb())).Logins;
            var result = manager.RemoveLogin(User.Identity.GetUserId(), loginProvider, providerKey);
            var msg = result.Success
                ? "?m=RemoveLoginSuccess"
                : String.Empty;
            Response.Redirect("~/Account/Manage.aspx" + msg);
        }

        private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
        }

        protected void ChangeNames_Click(object sender, EventArgs e)
        {
            var ctxt = new JustTestDb();
            string currentUser = Context.User.Identity.GetUserName();
            var user = ctxt.Users.FirstOrDefault(x => x.UserName == currentUser);

            using (ctxt)
            {
                user.FirstName = this.newFirstName.Text;
                user.LastName = this.newLastName.Text;
                ctxt.SaveChanges();
                Response.Redirect("~/Account/Manage.aspx?m=SetNamesSuccess");
            }
        }

        protected void ChangeProfilePicture_Click(object sender, EventArgs e)
        {
            if (FileUploadControl.HasFile)
            {
                System.IO.Stream fs = FileUploadControl.PostedFile.InputStream;
                System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
                Byte[] bytes = br.ReadBytes((Int32)fs.Length);
                string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
                choosenImage.ImageUrl = "data:image/png;base64," + base64String;
                choosenImage.Visible = true;

                var ctxt = new JustTestDb();
                string currentUser = Context.User.Identity.GetUserName();
                var user = ctxt.Users.FirstOrDefault(x => x.UserName == currentUser);

                using (ctxt)
                {
                    user.ProfilePicture = bytes;
                    ctxt.SaveChanges();
                }


                Response.Redirect("~/Account/Manage.aspx?m=SetPicSuccess");
            }
        }
    }
}